<?php
/*
 * Application base class
 * by xinqiyang  create 20091009  modify 20091009
 */
class BaseAction extends Action
{
	//页面信息数组
	var $page;
	
	protected function _bf_show($fn) { }
	protected function _bf_deal($fn) { }
	protected function _af_deal($fn) { }

	/**
	 * 初始化操作
	 */
	function _initialize()
	{
		if(method_exists($this,'_baseinit'))
		{
			//控制器初始化
			$this->_baseinit();
		}
	}

	/**
	 * router function to get the function action to deal
	 *
	 */
	public function _empty()
	{
		$this->deal();

	}

	/**
	 * 公共数据处理方法
	 * by xinqiyang
	 */
	public function deal()
	{

		if($this->getuid())
		{
			//TODO:这里进行验证
			$model = strtolower($_REQUEST['actm']);
			$model = (!empty($model)) ? $model : strtolower(ACTION_NAME);
			//dump($model.'   '.ACTION_NAME);
			$id = (int)$_REQUEST['id'];
			//dump($id);
			//获取模型及返回参数
			$arrmodel = array('ad','album','brand','comment','compaign','content','goods','group','image','log','mail','post','report','say','services','url','systemtree','topic','user');
			if(!$model || !in_array($model,$arrmodel))
			{
				echo 'system error';
				exit;
			}
			$ajax = (bool)$_REQUEST['ajax'];
			$d = D($model);
			//只能调用自己的资源了
			if($id)
			{
				if(GROUP_NAME == 'Web')
				{
					//dump('a');
					//如果是后台则可以直接调用
					//如果这里是topic则进行不同的调用了
					switch($model)
					{
						case 'topic':
						$instance = $d->where("id=$id and user_id=".$this->getuid())->find();
						$p = D('post');
						$instance['content'] = $p->getField('content','topic_id='.$id.' and istopic=1');
						//dump($p->getLastSQL());
						break;
						case 'user':
							$instance = $d->where("id=".$this->getuid())->find();
							break;
						default:
							$instance = $d->where("id=$id and user_id=".$this->getuid())->find();
					}
					//dump($instance);
					//没有权限则无法进行编辑
					if(!is_array($instance))
					{
						$this->noPage();
					}
				}else{
					$instance = $d->find($id);
				}
			}else{
				$instance =  $d->getOne();
			}
			//$instance = $id ?  $d->where('user_id='.$this->getuid())->find($id) : $d->getOne();
			

			if($this->isPost())
			{
				$type = $_POST['id'] ? 2 : 1;
				$return = '';
				if(method_exists($this,'_bf_deal'))
				{
					//对数据进行前期处理
					$this->_bf_deal($model);
				}
				if($d->create('',$type))
				{
					//处理上传
					if($_FILES['image_id']['name'])
					{
						$width = '120';
						$height ='120';
						if($model == 'brand')
						{
							$width = '70';
							$height ='50';
						}
						$image = $this->upload(ucwords($model),true,$width,$height);
						$d->image_id = $image;
					}else{
						//申明没有上传图片
						$noimg = true;
					}
					if($type == 2)
					{
						//更新信息,确保更新成功
						$d->user_id = $this->getuid();
						$d->save();
						$return = $_POST['id'];
						
					}else{
						//新增信息,user_id在auto里面自动处理了,如果auto不写则在这里处理
						$d->createtime = time();
						$d->user_id = $this->getuid();
						$return = $d->add();
					}
					//处理成功,则进行跳转
					if($return)
					{
						//处理下TAG
						tagDeal($_POST['tags'],$model,$return);
						//更新微博
						if($model == 'say')
						{
							D('user')->setField('microblog',remove_xss($_POST['content']),"id=".$this->getuid());	
						}
						if(method_exists($this,'_af_deal'))
						{
							
							//构建参数 
							$dealarr['id'] = $return;
							$dealarr['model'] = $model;
							$dealarr['img'] = $image;
							$dealarr['type'] = $type;
							//对数据进行后期处理
							$this->_af_deal($dealarr);
						}

						if($_REQUEST['jumpUrl'])
						{
							$this->assign('jumpUrl',$_REQUEST['jumpUrl']);
						}
						//TODO:提示信息到时候改改..呵呵
						$this->success("操作成功 ^_^",$ajax);
					}else{
						$this->error($d->getError(),$ajax);
					}
				}else{
					$this->error($d->getError(),$ajax);
				}

			}else{
				$this->assign('vo',$instance);
				if(method_exists($this,'_bf_show'))
				{
					$this->_bf_show($model);
				}
				if(GROUP_NAME == 'Web')
				{
					$this->t();
				}else{
					//显示模板
					$this->display();
				}
			}
		}else{
			echo 'system get error,please login'; exit;
		}
	}


	/**
	 * Common Upload Function
	 * @param unknown_type $module
	 * @param unknown_type $path
	 * @param unknown_type $thumb
	 * @param unknown_type $width
	 * @param unknown_type $height
	 */
	public function upload($module='',$thumb=true,$width=120,$height=120){
		$module= $module==''?'temp':$module;
		$path=C(ATTACHDIR).'/'.$module.'/mpic/';
		$spath = C(ATTACHDIR).'/'.$module.'/spic/';
		if (!is_dir($path))	@mk_dir($path);
		if (!is_dir($spath))	@mk_dir($spath);
		import("ORG.Net.UploadFile");
		$upload = new UploadFile();

		$upload->maxSize=3145728; //3M
		$upload->allowExts=array('jpg','gif','png','jpeg');
		$upload->savePath=$path;
		$upload->saveRule='uniqid';

		if($thumb)
		{
			$upload->thumb = true;
			$upload->thumbPrefix   =  '';
			$upload->thumbPath = $spath;
			$upload->thumbMaxWidth = $width;
			$upload->thumbMaxHeight = $height;
		}
		if(!$upload->upload()){
			//捕获上传异常
			$upl = $upload->getErrorMsg();
		}else{
			$upl = $upload->getUploadFileInfo();
		}
		//判断结果,插入数据库
		if(is_array($upl))
		{
			//插入图片表
			$img = M('image');
			
			$imgdata['model'] = $module;
			$imgdata['createtime'] = time();
			$imgdata['status'] = '1';
			$imgdata['url'] = C('ATTACHDIR');
			$imgdata['user_id'] = $this->getuid();
			$count = count($upl);
			//dump($count);
			if($count==1)
			{
				$imgdata['filename'] = $upl[0]['savename'];
				$imgid = $img->add($imgdata);
				return $imgid;
			}else{
				$str = '(';
				$counts = 0;
				for($i=0;$i<$count;$i++)
				{
					//dump($upl[$i]['savename']);
					$imgdata['filename'] = $upl[$i]['savename'];
					$imgid = $img->add($imgdata);
					if($imgid)
					{
						$str .= "'".$imgid."',";
						$counts ++;
					}
				}
				if($counts){
					//更新图片表
					return substr($str,0,-1).')';
				}
			}
		}else{
			//返回上传出错信息
			return $upl;
		}


	}

	/**
	 * find instance from db
	 * @param $model string Modelname
	 * @param $condition string Query Condition
	 * @param $field string Fields
	 */
	protected function find($model,$condition='',$field='*')
	{
		if($model)
		{
			$m = D($model);
			$list=$m->where($condition)->field($field)->find();
			return $list;
		}
		return 'null';
	}

	/**
	 * return Data Collection
	 * @param $model string ModelName
	 * @param $condition string Condition
	 * @param $order string ORDER
	 * @param $field string Fields
	 */
	protected function result($model,$condition='',$order='',$field='*')
	{

		if($model)
		{
			$m = D($model);
			//TODO:add more powerful this query
			$list=$m->where($condition)->order($order)->field($field)->select();
			//dump($m->getLastSQL()); exit;
			return $list;
		}
		return 'null';
	}

	/**
	 * layout show the template
	 * @param templatename $t
	 * @param templateinfo $info
	 */
	protected function t($t='')
	{
		if(empty($t))
		{
			$t = MODULE_NAME.':'.ACTION_NAME;
		}
		$this->assign('content',$t);
		$this->assign('page',$this->page);
		if(in_array(ACTION_NAME,array('goods','url','brand','cuticon','published','uploadimg','album','uploadmyimg','gomore')))
		{
			$this->display('Public:slayout');
		}else{
			//加载页面头部信息
			$this->display('Public:layout');
		}
	}
	
	

	/**
	 * 显示错误信息页面
	 */
	public function noPage()
	{
		//TODO:修改个比较个性化的404页面
		$this->t('Public:404');
	}

}


?>